<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <title>登录页面</title>
    <!-- 样 式 文 件 -->
    <link rel="stylesheet" th:href="@{/component/pear/css/pear.css}">
    <link rel="stylesheet" th:href="@{/admin/css/other/login.css}">
    <!-- 资 源 引 入 -->
    <script th:src="@{/component/layui/layui.js}"></script>
    <script th:src="@{/component/pear/pear.js}"></script>
    <script th:src="@{/js/jquery.js}"></script>
    <script th:src="@{/js/axios.min.js}"></script>
    <script th:src="@{/js/myjs/util.js}"></script>
    <style>
        .layadmin-user-jump-change {
            float: right;
        }
        .layadmin-link {
            color: #029789!important;
        }
        .layui-btn+.layui-btn {
            margin-left: 50px;
        }
        .layadmin-user-login-other>* {
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
            font-size: 14px;
        }
        .layadmin-user-login-other .layui-icon {
            position: relative;
            top: 2px;
            font-size: 26px;
        }
        .layui-icon-login-qq {
            color: #3492ED;
        }
        .layui-icon-login-wechat {
            color: #4DAF29;
        }
        .layui-icon-login-weibo {
            color: #CF1900;
        }
        .eye-icon{
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
        }
        .error{
            color: red;
            display: none;
        }
    </style>
</head>
<body th:background="@{/admin/images/background.svg}" style="background-size: cover;">
<form class="layui-form" id="login" lay-filter="login">
    <div class="layui-form-item">
        <img class="logo" th:src="@{/admin/images/logo.png}" />
        <div class="title">Wang Xue</div>
        <div class="desc">
            你 若 不 离 开，便 是 我 的 终 点。
        </div>
    </div>
    <div class="layui-form-item">
        <input placeholder="用户名/手机号/邮箱" type="text" autocomplete="username1" id="userInput" name="userInput"  class="layui-input"  />
        <span class="error" id="inputNull">用户名/手机号/邮箱不能为空</span>
        <span class="error" id="inputError">用户名/手机号/邮箱或密码错误</span>
        <span class="error" id="inputExist">该用户不存在，请重新输入</span>
    </div>
    <div class="layui-form-item">
        <input placeholder="密 码" type="password" id="password" autocomplete="current-password1" name="password" class="layui-input"  />
        <i class="layui-icon layui-icon-eye-invisible eye-icon" onclick="showPassword('password')"></i>
        <span class="error" id="passwordNull">密码不能为空</span>
    </div>
<!--    用户登录失败一次时显示验证码-->
    <div class="layui-form-item"  th:if="${session.showCaptcha}">
        <input placeholder="验证码"  id="captcha" name="captcha"  hover maxlength="4" minlength="4"  class="code layui-input layui-input-inline" />
        <img th:src="@{/captcha}"  id="captchaImage" class="codeImage"  onclick="changeCaptcha()" title="点击刷新验证码"/>
        <span class="error" id="captchaNull"><br /><br /><br />验证码不能为空</span>
        <span class="error" id="captchaError"><br /><br /><br />验证码错误</span>
    </div>
    <div class="layui-form-item">
        <input type="checkbox" name="" title="记住密码" lay-skin="primary">
        <a href="retrieve" class="layadmin-user-jump-change layadmin-link" style="margin-top: 7px">忘记密码？</a>
    </div>
    <div class="layui-form-item">
        <button type="submit" lay-filter="login" class="pear-btn pear-btn-success">登录</button>
    </div>
    <div class="layadmin-user-login-other">
        <label>社交账号登录</label>
        <a href="javascript:;"><i class="layui-icon layui-icon-login-qq"></i></a>
        <a href="javascript:;"><i class="layui-icon layui-icon-login-wechat"></i></a>
        <a href="javascript:;"><i class="layui-icon layui-icon-login-weibo"></i></a>
        <a href="register" class="layadmin-user-jump-change layadmin-link" style="margin-top: 5px">注册帐号</a>
    </div>
</form>

<button onclick="send()">发送</button>

<!--获取当前项目路径-->
<script type="text/javascript" th:inline="javascript">
    // thymeleaf 获取当前项目路径
    /*<![CDATA[*/
    const ctx = /*[[@{/}]]*/;
    /*]]>*/
    // 当前窗口 不是最外层窗口
    if (window != window.top){
        // 父窗口 window.parent，最外层窗口 window.top
        window.top.location.href = ctx;
    }
</script>

<!--刷新验证码-->
<script>
    // 刷新验证码
    function changeCaptcha() {
        // 获取验证码图片地址
        var captchaImg = document.getElementById('captchaImage');
        //重新获取验证码
        captchaImg.src = '/refreshCaptcha?' + Date.now();//加上时间戳，避免缓存
    }
</script>

<!--监听密码显示与隐藏-->
<script>
    // 监听小眼睛图标的点击事件
    function showPassword(id) {
        var input = document.getElementById(id);
        if (input.type === 'password') {
            input.type = 'text';
            input.className = 'layui-input';
        } else {
            input.type = 'password';
            input.className = 'layui-input layui-input-password';
        }
        var icon = input.nextElementSibling;
        icon.className = icon.className === 'layui-icon layui-icon-eye-invisible eye-icon' ? 'layui-icon layui-icon-eye eye-icon' : 'layui-icon layui-icon-eye-invisible eye-icon';
    }
</script>

<!--自动定位到用户名输入框-->
<script>
    window.onload = function() {
        var inputElement = document.getElementById("userInput");
        inputElement.focus();
    }
</script>

<!--判断输入框-->
<script>
    layui.use(['form', 'layer'], function() {
        var form = layui.form;
        var layer = layui.layer;

        document.querySelector('button[lay-filter="login"]').addEventListener('click', function(){
            // 获取用户名输入框的值
            let username = document.getElementById("userInput").value;
            let password = document.getElementById("password").value;
            let captcha = document.getElementById("captcha").value;
            if (username == '' || username == null) {
                document.getElementById('inputNull').style.display = 'inline';
                document.getElementById('userInput').focus();
            } else if (password == '' || password == null) {
                document.getElementById('passwordNull').style.display = 'inline';
                document.getElementById('password').focus();
            } else if (captcha == '' || captcha == null) {
                document.getElementById('captchaNull').style.display = 'inline';
                document.getElementById('captcha').focus();
                document.getElementById('captchaError').style.display = 'none';
            } else {
                return true;
            }
        })

        // 判断验证码是否正确
        $(document).ready(function () {
            $("#captcha").blur(function () {
                var captcha = $(this).val();
                var captchaError = document.getElementById('captchaError');
                var captchaNull = document.getElementById('captchaNull');
                if (captcha == null || captcha == "") {
                    captchaNull.style.display = 'inline';
                    captchaError.style.display = 'none';
                } else {
                    captchaNull.style.display = 'none';
                }
                // 异步验证验证码是否正确
                if (captcha) {
                    $.ajax({
                        url: "/captcha", // 后端验证接口地址
                        type: "POST",
                        data: {
                            captcha: captcha
                        },
                        success: function (response) {// 成功回调函数
                            if (response === "success") {
                                console.log("验证码正确");
                                captchaError.style.display = 'none';
                                return true;
                            } else {
                                console.log("验证码错误");
                                captchaError.style.display = 'inline';
                                //刷新验证码
                                changeCaptcha();
                                //清空验证码输入框
                                document.getElementById('captcha').value = "";
                                document.getElementById('captcha').focus();
                                return false;
                            }
                        },
                        error: function () {
                            console.log("请求后端验证接口失败");
                            // 显示500页面
                            window.location.href = "/500";
                        }
                    });
                }
            });
        });

        // 加载js加密插件
        var respPublicKey;// 后端返回的公钥
        $(document).ready(function() {
            addScript("/js/jsencrypt.min.js");
            $.ajax({
                url: '/public-key', // 发起GET请求到/public-key端点
                type: 'GET',
                success: function (publicKey) {
                    // 在请求成功时，publicKey参数将包含后端返回的公钥字符串
                    console.log('Received public key:', publicKey);
                    respPublicKey = publicKey; // 将公钥存储在全局变量中
                },
                error: function () {
                    // 在请求失败时的处理逻辑
                    console.error('Failed to retrieve public key');
                }
            });
            $('#login').on('submit', function (event) {
                event.preventDefault();// 阻止表单默认提交事件
                var input = $('#userInput').val();// 手机号
                var password = $('#password').val();// 密码

                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(respPublicKey);
                var encryptInput= encrypt.encrypt(input);
                var encryptPassword = encrypt.encrypt(password);

                $.ajax({
                    url: '/login',
                    type: 'POST',
                    data: {
                        userInput: encryptInput,
                        password: encryptPassword,
                    },
                    success: function (response) {
                        // 提交成功的处理逻辑
                        // 处理后端返回的结果
                        console.log(response);
                        if (response.code === 200) {
                            window.location.href = ctx + response.data;
                        } else {
                            if (response.code === 205) {
                                // console.log(response.msg);
                                document.getElementById("inputNull").style.display = 'inline';
                            } else if (response.code === 400) {
                                console.log(response.msg);
                                // 刷新验证码
                                changeCaptcha();
                                document.getElementById("inputError").style.display = 'inline';
                                // 清空验证码输入框
                                document.getElementById('captcha').value = "";
                                document.getElementById("userInput").focus();
                            } else {
                                window.location.href = ctx + "util/402";
                            }
                        }
                    }, error: function (error) {
                        console.log(error);
                        window.location.href = ctx + "util/500";
                    }
                });
                return false;
            });
        });

        //输入框失去焦点
        $('#userInput').on('input', function () {
            if (document.getElementById("userInput").value !== '' || document.getElementById("userInput").value !== null) {
                document.getElementById('inputNull').style.display = 'none';
            } else {
                document.getElementById('inputNull').style.display = 'none';
            }
        })
        document.getElementById("userInput").addEventListener("blur", function (e) {
            if (document.getElementById("userInput").value == '' || document.getElementById("userInput").value == null) {
                document.getElementById('inputNull').style.display = 'inline';
                //焦点
                document.getElementById("userInput").focus();
            } else {
                document.getElementById('inputNull').style.display = 'none';
            }
        });

        //密码失去焦点
        $('#password').on('input', function () {
            if (document.getElementById("password").value !== '' || document.getElementById("password").value !== null) {
                document.getElementById('passwordNull').style.display = 'none';
            } else {
                document.getElementById('passwordNull').style.display = 'none';
            }
        })
        document.getElementById("password").addEventListener("blur", function (e) {
            if (document.getElementById("password").value === '' || document.getElementById("password").value == null) {
                document.getElementById('passwordNull').style.display = 'inline';
                //焦点
                document.getElementById("password").focus();
            } else {
                document.getElementById('passwordNull').style.display = 'none';
            }
        });
    })
</script>

<!-- 测试防刷脚本-->
<script>
    function send() {
        for (let i = 0; i < 100; i++) {
            // 发送请求
            fetch("/login", {
                method: "get",
                headers: {
                    "Content-Type": "application/json"
                },
                //跳转到403页面
                redirect: "manual"
            }).then(function (response) {
                // 处理响应
                if (response.status === 403) {
                    // 跳转到403页面
                    window.location.href = ctx + "util/403";
                    return false;
                } else {
                    // 跳转到登录页面
                    window.location.href = ctx + "login";
                }
            });
        }
    }
</script>
</body>
</html>